<template>
    <div class="page-container">
        <TableHead
            :config="tableHeaderConfig"
            :searchdata.sync="filters"
            v-show="showSearch"
            @parentPageList="findPageList"
        >
            <el-select v-model="filters.appId" slot="app" placeholder="请选择" size="mini">
                <el-option v-for="item in appList" :key="item.id" :label="item.appName" :value="item.id" />
            </el-select>
        </TableHead>
        <!--表格内容栏-->
        <el-card class="card-box">
            <table-tool-bar :showSearch.sync="showSearch" @queryTable="findPageList" :columns="columns">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            </table-tool-bar>
            <Table
                v-model="filters.pageNum"
                :columns="columns"
                :data="tableList"
                :total="total"
                :loading="loading"
                showNo
                @getPageList="findPageList"
            >
                <template slot="isValid" slot-scope="{ scope }">
                    <el-switch
                        v-model="scope.row.isValid"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleEnable(scope.row)"
                    ></el-switch>
                </template>
                <template slot="oper" slot-scope="{ scope }">
                    <el-button
                        size="mini"
                        type="text"
                        v-if="scope.row.isValid === 1"
                        icon="el-icon-edit"
                        @click="handleEdit(scope.row)"
                    >
                        编辑
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">
                        删除
                    </el-button>
                    <el-button
                        size="mini"
                        v-if="scope.row.isValid === 1"
                        type="text"
                        icon="el-icon-user"
                        @click="handleUser(scope.row)"
                    >
                        用户
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        v-if="scope.row.isValid === 1"
                        class="icon iconfont icon-tongyong-anquan"
                        @click="handleRole(scope.row)"
                    >
                        授权
                    </el-button>
                </template>
            </Table>
        </el-card>
        <!--新增与编辑的弹窗-->
        <EditItem
            v-model="dialogVisible"
            :data-form="dataForm"
            :dialog-config="dialogConfig"
            :data-form-rules="dataFormRules"
            :dialog-tag="dialogTag"
            :title="title"
            width="600px"
            @submitForm="submitForm"
        >
            <el-select
                v-model="dataForm.appId"
                slot="appId"
                placeholder="请选择应用"
                size="small"
                class="width100"
                :disabled="dialogTag === 'edit'"
            >
                <el-option v-for="item in appList" :key="item.id" :label="item.appName" :value="item.id" />
            </el-select>
        </EditItem>
        <!--角色菜单，表格树内容栏-->
        <RoleTree
            :select-role="selectRole"
            :appId="appId"
            :roleId="roleId"
            :title="roleDialogTitle"
            v-model="roleVisible"
        />
    </div>
</template>

<script>
import TableHead from '@/components/TableHeadSearch'
import TableToolBar from '@/components/TableToolBar'
import EditItem from '@/components/EditItem'
import RoleTree from './roleTree'
import {
    getRoleList,
    addRole,
    editRole,
    deleteRole,
    roleEnable
    // roleBindMenu,
    // getAllMenuByApp,
    // getMenuByRole
} from '@/api/system/user'
import { appManagerPageList } from '@/api/system/application'

import { confirm } from '@/utils/utils'

export default {
    name: 'role',
    components: {
        TableHead,
        EditItem,
        RoleTree,
        TableToolBar
    },
    data() {
        return {
            title: '新增角色',
            showSearch: true,
            // 表格要查询的字段配置
            filters: {
                roleName: '',
                appId: '',
                isValid: null,
                pageNum: 1,
                pageSize: 10
            },
            appList: [],
            loading: false,
            // 表格搜索处的字段
            tableHeaderConfig: [
                { title: '角色名', code: 'roleName', type: 'input' },
                { title: '应用', slot: 'app' },
                { title: '是否启用', code: 'isValid' }
            ],
            // 列表的列的展示字段
            columns: [
                { prop: 'roleName', label: '角色名', visible: true, key: 'roleName' },
                { prop: 'appName', label: '应用名', visible: true, key: 'appName' },
                { slot: 'isValid', label: '状态', visible: true, key: 'isValid' },
                {
                    prop: 'description',
                    label: '描述',
                    minWidth: 200,
                    showOverflowTooltip: true,
                    visible: true,
                    key: 'description'
                },
                { label: '创建人/创建时间', type: 'createUser', visible: true, key: 'createUser' },
                { label: '更新人/更新时间', type: 'updateUser', visible: true, key: 'updateUser' },
                {
                    slot: 'oper',
                    label: '操作',
                    align: 'center',
                    minWidth: 120,
                    fixed: 'right',
                    visible: true,
                    key: 'oper'
                }
            ],
            // 接口返回data
            tableList: [],
            total: 0,
            // 新增编辑界面是否显示
            dialogVisible: false,
            // 规则
            dataFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名', trigger: 'blur' },
                    {
                        max: 10,
                        message: '长度在10 个字符以内',
                        trigger: 'blur'
                    }
                ],
                appId: [{ required: true, message: '请选择应用', trigger: 'change' }]
            },
            // 新增编辑界面数据
            dataFormDefault: {
                id: '',
                appId: '',
                description: '',
                isValid: 1,
                roleName: ''
            },
            dataForm: {},
            // dialog 要渲染的数据json
            dialogConfig: [
                { title: '角色名', code: 'roleName', type: 'input', maxlength: 10 },
                { title: '应用', slot: 'appId', code: 'appId' },
                {
                    title: '角色描述',
                    code: 'description',
                    type: 'textarea',
                    maxlength: 20
                }
            ],
            dialogTag: '', // 编辑与新样的标识
            // 下面的菜单：：：：
            selectRole: {},
            roleVisible: false,
            roleId: 0,
            appId: 0,
            roleDialogTitle: ''
        }
    },
    mounted() {},
    created() {
        this.findPageList()
        this.getAppList()
    },
    activated() {
        this.findPageList()
        this.getAppList()
    },
    methods: {
        // 获取分页数据
        findPageList() {
            this.loading = true
            getRoleList(this.filters)
                .then((res) => {
                    this.tableList = res.data.items
                    this.total = res.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },
        getAppList() {
            appManagerPageList({ isValid: 1 }).then((res) => {
                this.appList = res.data
            })
        },
        // 删除
        handleDelete(id) {
            confirm('确定要删除吗').then(() => {
                deleteRole({ roleId: id }).then((res) => {
                    this.$message.success(res.msg)
                    this.findPageList()
                })
            })
        },
        handleEnable(row) {
            let tip = row.isValid === 0 ? '禁用该角色后，角色下绑定的用户直接解绑，确认要禁用吗?' : '确定启用该角色吗?'
            confirm(tip)
                .then(() => {
                    roleEnable({ roleId: row.id, isValid: row.isValid })
                        .then((res) => {
                            this.$message.success(res.msg)
                            this.findPageList()
                        })
                        .catch(() => {
                            row.isValid = row.isValid === 0 ? 1 : 0
                        })
                })
                .catch(() => {
                    row.isValid = row.isValid === 0 ? 1 : 0
                })
        },
        // 选择用户
        handleUser(row) {
            this.$router.push('/system/role-auth/user/' + row.id + '/' + row.roleName)
        },
        // 显示新增界面
        handleAdd() {
            this.dialogVisible = true
            this.dataForm = Object.assign({}, this.dataFormDefault)
            this.dialogTag = 'add'
        },
        // 显示编辑界面
        handleEdit(params) {
            this.title = '编辑角色'
            this.dialogVisible = true
            this.dataForm = Object.assign({}, params)
            this.dialogTag = 'edit'
        },
        // 编辑与新增 提交 请求接口
        submitForm(data) {
            let fetchApi = this.dialogTag === 'add' ? addRole : editRole
            fetchApi(data).then((res) => {
                this.$message.success(res.msg)
                this.findPageList()
                this.dataForm = Object.assign({}, this.dataFormDefault)
                this.dialogVisible = false
            })
        },
        handleRole(row) {
            this.selectRole = row
            this.roleVisible = true
            this.roleDialogTitle = `角色授权(${row.roleName})`
        }
        // 角色选择改变监听
        // handleRoleSelectChange(val) {
        //   if (val == null || val.val == null) {
        //     return;
        //   }
        //   this.selectRole = val.val;
        //   this.$api.role.findRoleMenus({ roleId: val.val.id }).then(res => {
        //     this.currentRoleMenus = res.data;
        //     this.$refs.menuTreeref.$refs.menuTree.setCheckedNodes(res.data);
        //   });
        // }
    }
}
</script>
<style scoped></style>
